// server/src/controllers/authController.ts
import { Request, Response } from 'express'
import { prisma } from '../lib/prisma'
import { generateToken, verifyPassword, hashPassword, generateRandomToken } from '../utils/auth'
import { sendSuccess, sendError } from '../utils/response'
import { AuthRequest } from '../middleware/auth'

export const login = async (req: Request, res: Response) => {
  try {
    const { username, password } = req.body

    if (!username || !password) {
      return sendError(res, '用户名和密码不能为空')
    }

    // 查找用户
    const user = await prisma.user.findFirst({
      where: {
        OR: [
          { username },
          { email: username }
        ],
        isActive: true
      }
    })

    if (!user) {
      return sendError(res, '用户不存在或已被禁用', 401)
    }

    // 验证密码
    const isValidPassword = await verifyPassword(password, user.password)
    if (!isValidPassword) {
      return sendError(res, '密码错误', 401)
    }

    // 生成 JWT Token
    const token = generateToken({
      userId: user.id,
      username: user.username,
      role: user.role
    })

    // 更新最后登录时间
    await prisma.user.update({
      where: { id: user.id },
      data: { lastLoginAt: new Date() }
    })

    sendSuccess(res, {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar
      }
    }, '登录成功')
  } catch (error) {
    console.error('Login error:', error)
    sendError(res, '登录失败，请稍后重试')
  }
}

export const register = async (req: Request, res: Response) => {
  try {
    const { username, email, password, confirmPassword } = req.body

    if (!username || !email || !password) {
      return sendError(res, '请填写所有必填字段')
    }

    if (password !== confirmPassword) {
      return sendError(res, '两次输入的密码不一致')
    }

    if (password.length < 6) {
      return sendError(res, '密码长度至少6位')
    }

    // 检查用户是否已存在
    const existingUser = await prisma.user.findFirst({
      where: {
        OR: [
          { username },
          { email }
        ]
      }
    })

    if (existingUser) {
      return sendError(res, '用户名或邮箱已存在')
    }

    // 加密密码
    const hashedPassword = await hashPassword(password)

    // 创建用户
    const user = await prisma.user.create({
      data: {
        username,
        email,
        password: hashedPassword,
        role: 'USER',
        isActive: true,
        avatar: null
      }
    })

    // 生成 JWT Token
    const token = generateToken({
      userId: user.id,
      username: user.username,
      role: user.role
    })

    sendSuccess(res, {
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        role: user.role,
        avatar: user.avatar
      }
    }, '注册成功')
  } catch (error) {
    console.error('Register error:', error)
    sendError(res, '注册失败，请稍后重试')
  }
}

export const getProfile = async (req: AuthRequest, res: Response) => {
  try {
    const user = await prisma.user.findUnique({
      where: { id: req.userId },
      select: {
        id: true,
        username: true,
        email: true,
        role: true,
        avatar: true,
        isActive: true,
        createdAt: true,
        lastLoginAt: true
      }
    })

    if (!user) {
      return sendError(res, '用户不存在', 404)
    }

    sendSuccess(res, { user }, '获取个人信息成功')
  } catch (error) {
    console.error('Get profile error:', error)
    sendError(res, '获取个人信息失败')
  }
}

export const updateProfile = async (req: AuthRequest, res: Response) => {
  try {
    const { username, email, avatar } = req.body

    // 检查用户名和邮箱是否已被其他用户使用
    if (username || email) {
      const existingUser = await prisma.user.findFirst({
        where: {
          AND: [
            { id: { not: req.userId } },
            {
              OR: [
                ...(username ? [{ username }] : []),
                ...(email ? [{ email }] : [])
              ]
            }
          ]
        }
      })

      if (existingUser) {
        return sendError(res, '用户名或邮箱已被使用')
      }
    }

    const updatedUser = await prisma.user.update({
      where: { id: req.userId },
      data: {
        ...(username && { username }),
        ...(email && { email }),
        ...(avatar && { avatar })
      },
      select: {
        id: true,
        username: true,
        email: true,
        role: true,
        avatar: true
      }
    })

    sendSuccess(res, { user: updatedUser }, '更新个人信息成功')
  } catch (error) {
    console.error('Update profile error:', error)
    sendError(res, '更新个人信息失败')
  }
}

export const changePassword = async (req: AuthRequest, res: Response) => {
  try {
    const { currentPassword, newPassword, confirmPassword } = req.body

    if (!currentPassword || !newPassword) {
      return sendError(res, '请填写所有密码字段')
    }

    if (newPassword !== confirmPassword) {
      return sendError(res, '两次输入的新密码不一致')
    }

    if (newPassword.length < 6) {
      return sendError(res, '新密码长度至少6位')
    }

    // 获取当前用户
    const user = await prisma.user.findUnique({
      where: { id: req.userId }
    })

    if (!user) {
      return sendError(res, '用户不存在', 404)
    }

    // 验证当前密码
    const isValidPassword = await verifyPassword(currentPassword, user.password)
    if (!isValidPassword) {
      return sendError(res, '当前密码错误', 401)
    }

    // 加密新密码
    const hashedPassword = await hashPassword(newPassword)

    // 更新密码
    await prisma.user.update({
      where: { id: req.userId },
      data: { password: hashedPassword }
    })

    sendSuccess(res, null, '密码修改成功')
  } catch (error) {
    console.error('Change password error:', error)
    sendError(res, '密码修改失败')
  }
}

export const logout = async (req: AuthRequest, res: Response) => {
  try {
    // 在实际应用中，你可能需要将 token 加入黑名单
    // 这里只是返回成功消息，由客户端删除 token
    sendSuccess(res, null, '退出登录成功')
  } catch (error) {
    console.error('Logout error:', error)
    sendError(res, '退出登录失败')
  }
}